package com.zhongya.example.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.zhongya.example.R
import kotlin.math.atan2
import kotlin.properties.Delegates

class GetPosTanView : View {

    lateinit var mCirclePath : Path
    lateinit var mDstPath : Path
    lateinit var mPaint : Paint
    lateinit var mPathMeasure : PathMeasure
    var mCurAnimValue by Delegates.notNull<Float>()
    lateinit var mArrawBmp : Bitmap

    private val pos = FloatArray(2)
    private val tan = FloatArray(2)


    constructor(context: Context) : super(context) {

    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        setLayerType(LAYER_TYPE_SOFTWARE,null)
        mArrawBmp = BitmapFactory.decodeResource(resources, R.drawable.arrow_right)

        //画笔
        mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeWidth = 4f
        mPaint.color = Color.BLACK
        //路径
        mDstPath = Path()
        mCirclePath = Path()
        mCirclePath.addCircle(300f,300f,150f,Path.Direction.CW)

        mPathMeasure = PathMeasure(mCirclePath,true)

        val animator = ValueAnimator.ofFloat(0f,1f)
        animator.repeatCount = ValueAnimator.INFINITE
        animator.addUpdateListener {
            mCurAnimValue =  animator.animatedValue as Float
            invalidate()
        }
        animator.duration = 2000
        animator.start()

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //绘制路径动画
        canvas?.drawColor(Color.WHITE)
        val stop = mPathMeasure.length*mCurAnimValue
        mDstPath.reset()
        mPathMeasure.getSegment(0f,stop,mDstPath,true)
        canvas?.drawPath(mDstPath,mPaint)

        //旋转箭头图片，并绘制
        mPathMeasure.getPosTan(stop,pos,tan)
        val degrees = (atan2(tan[1].toDouble(),tan[0].toDouble()) * 180/ Math.PI).toFloat()
        val matrix = Matrix()
        matrix.postRotate(degrees,mArrawBmp.width / 2f,mArrawBmp.height/2f)
        matrix.postTranslate(pos[0] - mArrawBmp.width/2,pos[1] - mArrawBmp.height/2)
        canvas?.drawBitmap(mArrawBmp,matrix,mPaint)
    }
}